<template>
    <div class="">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div>
                <searchrevealing>
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="78px">
                        <el-form-item label="招商部" prop="recruiterDept">
                            <el-select style="width: 220px" v-model="queryParams.recruiterDept" placeholder="请选择招商部"
                                clearable @change="deptChange">
                                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="招商员" prop="recruiter">
                            <el-select style="width: 220px" v-model="queryParams.recruiter" placeholder="请选择招商员"
                                clearable>
                                <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="到样日期" prop="arrivalTimeStr">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.arrivalTimeStr" type="date" placeholder="请选择到样日期"
                                clearable style="width: 220px" />
                        </el-form-item>
                        <el-form-item label="上架状态" prop="status">
                            <el-select v-model="queryParams.status" placeholder="请选择上架状态" clearable
                                style="width: 220px">
                                <el-option v-for="dict in statusList" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">查询</el-button>
                            <el-button @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </searchrevealing>
                <el-card shadow="never">
                    <template #header>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="1.5">
                                <el-button type="primary" :disabled="multiple" @click="listing">上架</el-button>
                            </el-col>
                            <!-- <el-col :span="1.5">
                                <el-button type="primary" :disabled="multiple" @click="handleExport">导出</el-button>
                            </el-col> -->
                            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                        </el-row>
                    </template>
                    <el-table v-loading="loading" :data="selectionRecordList" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="序号" type="index" width="55" align="center" />
                        <el-table-column label="商品名称" align="center" prop="styleName" />
                        <el-table-column label="商品编码" align="center" prop="styleCode" />
                        <el-table-column label="商品主图" align="center" prop="productImage" width="100">
                            <template #default="scope">
                                <image-preview :src="scope.row.productImage" :width="50" :height="50" />
                            </template>
                        </el-table-column>
                        <el-table-column label="价格" align="center" prop="price" />
                        <el-table-column label="机制" align="center" prop="liveStreamingMechanism" />
                        <el-table-column label="佣金" align="center" prop="commission" />
                        <el-table-column label="类目" align="center" prop="categoryName" />
                        <el-table-column label="品牌" align="center" prop="brand">
                            <template #default="scope">
                                {{ handleFilterBrand(scope.row.brand, brandList) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="店铺名称" align="center" prop="storeName" />
                        <el-table-column label="招商员" align="center" prop="recruiter" />
                        <el-table-column label="寄样时间" align="center" prop="updateTime" />
                        <el-table-column label="到样时间" align="center" prop="arrivalTime" />
                        <el-table-column label="收货人" align="center" prop="operatorBy" />
                        <el-table-column label="对品人" align="center" prop="checkedBy" />
                        <el-table-column label="状态" align="center" prop="status">
                            <template #default="scope">
                                <div>{{ getStatusName(scope.row.status) }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-button link type="primary" @click="listing(scope.row)"
                                    :disabled="scope.row.status !== '1'">
                                    上架</el-button>
                                <el-button link type="primary" @click="freightFeedback(scope.row)"
                                    style="margin-left: 0px !important" :disabled="scope.row.status !== '1'">
                                    运损反馈</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize" @pagination="getList" />
                </el-card>
                <el-dialog v-model="freightFeedbackFlag" title="运货反馈" width="500" style="padding: 0 20px"
                    :before-close="freightFeedbackCancel">
                    <div class="des">
                        请确认以下样品属于运损状态
                    </div>
                    <div>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="6">
                                商品编码：
                            </el-col>
                            <el-col :span="16">
                                {{ freightFeedbackForm.styleCode }}
                            </el-col>
                        </el-row>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="6">
                                商品名称：
                            </el-col>
                            <el-col :span="16">
                                {{ freightFeedbackForm.styleName }}
                            </el-col>
                        </el-row>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="6">
                                到样时间：
                            </el-col>
                            <el-col :span="16">
                                {{ freightFeedbackForm.arrivalTime }}
                            </el-col>
                        </el-row>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="6">
                                对品人：
                            </el-col>
                            <el-col :span="16">
                                {{ freightFeedbackForm.checkedBy }}
                            </el-col>
                        </el-row>
                    </div>
                    <div class="message">
                        提示：供应商重新补样请点击报损并邀约，否则请点击进行报损
                    </div>
                    <template #footer>
                        <div class="dialog-footer">
                            <!-- <el-button :loading="buttonLoading" type="" @click="">仅报损</el-button> -->
                            <el-button :loading="buttonLoading" type="primary"
                                @click="handleDamageInviteId">报损并邀约</el-button>
                        </div>
                    </template>
                </el-dialog>
            </div>
        </transition>
        <!-- 上架前一维码打印 -->
        <printing @doClose="printingClose" :printingVisible="printingVisible" :printingNumber="printingNumber" />
    </div>
</template>

<script setup name="SampleRecord" lang="ts">
import { getDeptList, getUserById } from '@/api/group/qualityControl'
import { SelectionRecordQueryParams, SelectionRecordVO } from '@/api/group/investmentPromotion/types'
import { listBrand } from '@/api/system/brand';
import { BrandVO } from '@/api/system/brand/types';
import { auditStatusNameById } from '@/utils/auditStatusFilter'
import printing from './printing.vue'
import { productsBusinessList, putOn, damageInviteId, productsBusinessExport } from '@/api/group/investmentPromotion/index'


const queryFormRef = ref<ElFormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const buttonLoading = ref(false);
const printingVisible = ref<boolean>(false)
const printingNumber = ref<string>('')
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const brandList = ref<BrandVO[]>([]);
const ids = ref<Array<string | number>>([]);
const idsList = ref<{ productsId?: string; inventory?: string; }[]>([]);
const names = ref<string[]>()
const multiple = ref(true);
const selectionRecordList = ref<SelectionRecordVO[]>([]);
const freightFeedbackFlag = ref(false)
const freightFeedbackForm = ref<SelectionRecordVO | any>({})
const selections = ref()
const queryParams = ref<SelectionRecordQueryParams>({
    pageNum: 1,
    pageSize: 10,
    dept: undefined,
    recruiter: undefined,
    arrivalTimeStr: undefined,
    status: undefined,
    recruiterDept: undefined
})
const statusList = [
    {
        label: '未到货', value: '0'
    },
    {
        label: '已到货', value: '1'
    },
    {
        label: '破损邀约', value: '2'
    },
    {
        label: '入库', value: '3'
    },
    {
        label: '退还给供应商', value: '4'
    },
]

//** 反查status */
const getStatusName = (status?: string) => {
    return statusList.filter(item => item.value == status)[0].label
}
/**
 * 获取招商部门信息
 */
const getDeptLists = async () => {
    const res = await getDeptList({ parentId: '1782395704411734018' })
    deptList.value = res.data
}
/** 报损并邀约 */
const handleDamageInviteId = async () => {
    await damageInviteId([{ id: freightFeedbackForm.value.id, productsId: freightFeedbackForm.value.productsId }])
    proxy?.$modal.msgSuccess('报损并邀约成功');
    freightFeedbackFlag.value = false;
    getList();
}
/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserById(event)
        recruiterList.value = res.data
        queryParams.value.recruiter = undefined
    } else {
        recruiterList.value = []
        queryParams.value.recruiter = undefined
    }
}
// 运损反馈
const freightFeedback = (row: SelectionRecordVO) => {
    freightFeedbackFlag.value = true;
    freightFeedbackForm.value = row
}
// 运损反馈关闭
const freightFeedbackCancel = () => {
    freightFeedbackFlag.value = false
}

/** 导出按钮操作 */
const handleExport = async () => {
    const idsList = ids.value.map(item => ({ id: item }))
    // await productsBusinessExport(idsList)
    proxy?.download("/electroniccommerce/productsBusiness/export", {
        id: ids.value
    }, `productsBusiness_${new Date().getTime()}.xlsx`)
}

/**
 * 上架
 */
const listing = async (row?: any) => {
    // const _id = row?.id || ids.value;
    // printingVisible.value = true
    // printingNumber.value = row?.productsId
    if (!row.styleName) {
        const flag = selections.value.every((item: { status: string; }) => item.status == '1')
        if (!flag) {
            ElMessage.error('请选择状态为已到货中的商品');
        } else {
            const _names = row.styleName || names.value;
            await proxy?.$modal.confirm('是否确认上架商品，商品名称为"' + _names + '"的数据项？').finally(() => (loading.value = false));
            const idsLists = row.id ? [{ id: row.id, inventory: row.inventory }] : idsList.value
            await putOn(idsLists)
            proxy?.$modal.msgSuccess('上架成功');
            getList();
        }
    } else {
        const _names = row.styleName || names.value;
        await proxy?.$modal.confirm('是否确认上架商品，商品名称为"' + _names + '"的数据项？').finally(() => (loading.value = false));
        const idsLists = row.id ? [{ id: row.id, inventory: row.inventory }] : idsList.value
        await putOn(idsLists)
        proxy?.$modal.msgSuccess('上架成功');
        getList();
    }
};
/**
 * 商家关闭
 */
const printingClose = () => {
    printingVisible.value = false
    printingNumber.value = ''
};
/**
 * 获取品牌信息
 */
const getListBrand = async () => {
    const res = await listBrand()
    brandList.value = res.rows;
}
/**
 * 品牌检索value
 * @param para 
 * @param dict 
 */
const handleFilterBrand = (para: string | number | undefined, dict: Array<any>) => {
    let _label = '';
    dict.forEach((item: any) => {
        if (item.id == String(para)) {
            _label = item.brandName;
        }
    });
    return _label;
};
/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        console.log(queryParams.value)
        const res = await productsBusinessList(queryParams.value);
        selectionRecordList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SelectionRecordVO[]) => {
    ids.value = selection.map((item) => item.id);
    names.value = selection.map((item) => item.styleName);
    idsList.value = selection.map((item) => ({ id: item.id, inventory: item.inventory }));
    multiple.value = !selection.length;
    selections.value = selection
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
onMounted(() => {
    queryParams.value.pageNum = 1;
    getListBrand();
    getDeptLists();
    getList();
})

</script>
<style lang="scss" scoped>
.des {
    margin-bottom: 20px;
}

.message {
    margin-right: 10px 0;
    color: red;
}
</style>
